package com.godenwater.recv.server.all;


import com.godenwater.recv.handler.*;
import com.godenwater.recv.model.CommonMessage;
import com.godenwater.recv.server.hd.HdMessageHeader;
import com.godenwater.recv.server.yln.YlnMessageHeader;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 报文接收处理器，为加快报文的处理，对接收后的报文仅保存为文件，以提高接收的效率
 *
 * @author 李普军
 * @date 2016-10-18
 */
public class ServerDataHandler extends IoFilterAdapter implements IoHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private final RtuServer server;

    private String channel;
    private int port;


    public ServerDataHandler(RtuServer server, String channel, int port) {
        this.server = server;
        this.channel = channel;
        this.port = port;

    }

    /**
     * 消息接收后的处理，只处理业务逻辑，此消息处理是在解码后，所以只需要关注消息体的内容
     */
    public void messageReceived(IoSession session, Object message)
            throws Exception {

//        logger.debug("接收通道" + this.channel + " 服务端已收到 " + server.messageSize() + " 消息数;");

        // if (message instanceof IoBuffer) {
        // System.out.println(">>> HydroServerHandler message is IoBuffer ");
        // }

        // Collection<IoSession> sessions =
        // session.getService().getManagedSessions().values();
        // // 向所有客户端发送数据
        // for (IoSession sess : sessions) {
        // sess.write("sessionId" + "\t" + sess.getId());
        // }

        if (message instanceof CommonMessage) {
            // 纯粹只处理报文，此消息体已经被解码为单体报文

            CommonMessage msg = (CommonMessage) message;
            Object msgheader = msg.getHeader();
            if (msgheader instanceof cn.gov.mwr.sl651.header.HexHeader) {

                // sl651MessageHandler(session, msg);
                Sl651MessageHandler.getInstance().perform(channel, session, msg, port);

            } else if (msgheader instanceof cn.gov.mwr.sl651.header.AscHeader) {

                //sl651MessageHandler(session, msg);
                Sl651MessageHandler.getInstance().perform(channel, session, msg, port);

            } else if (msgheader instanceof com.godenwater.yanyu.YYMessageHeader) {

                // yyMessageHandler(session, msg);
                YanyuMessageHandler.getInstance().perform(channel, session, msg, port);

            } else if (msgheader instanceof cn.gov.mwr.szy206.SzyMessageHeader) {

                // szy206MessageHandler(session, msg);
                Szy206MessageHandler.getInstance().perform(channel, session, msg, port);

            } else if (msgheader instanceof HdMessageHeader) {

                HdMessageHandler.getInstance().perform(channel, session, msg, port);

            } else if (msgheader instanceof YlnMessageHeader) {

                YlnMessageHandler.getInstance().perform(channel, session, msg, port);

            } else {
                // 未知的报文,供扩展处理用
            }
        }

        // 存储测站与session关联
        // RtuServer.getInstance().getSessionManager().addClient(stcd, session);

        // HydroServer.getInstance().getMonitorManager().append(log.toString());
        // 启动重发机制
    }

    /**
     * {@inheritDoc}
     */
    public void sessionClosed(IoSession session) throws Exception {
        logger.debug("关闭会话  " + session.getRemoteAddress());
//        logger.debug("关闭会话  ");
        RtuServer.getInstance().getSessionManager().removeSession(session);
    }

    /**
     * 当session创建连接后，需添加到一个客户端中
     */
    public void sessionCreated(IoSession session) throws Exception {
//        logger.debug("----------------------------------------------------------------------");
//        logger.debug("创建会话  " + session.getRemoteAddress());
//        logger.debug("创建会话  ");
        RtuServer.getInstance().getSessionManager().createSession(session);
    }

    /**
     * {@inheritDoc} 在此对空闲的session进行关闭
     */
    public void sessionIdle(IoSession session, IdleStatus status)
            throws Exception {
//        logger.debug("空闲会话  " + session.getRemoteAddress());
//        logger.debug("空闲会话  ");
        RtuServer.getInstance().getSessionManager().idleSession(session);
    }

    /**
     * /**
     * {@inheritDoc}
     */
    public void sessionOpened(IoSession session) throws Exception {
        // logger.info("Session Opened...");

    }

    public void exceptionCaught(IoSession session, Throwable cause)
            throws Exception {
        logger.debug("会话出现异常  " + session.getRemoteAddress() + " \t" + cause.getMessage());
//        logger.debug("会话出现异常  ");
        RtuServer.getInstance().getSessionManager().removeSession(session);
    }

    /**
     * 消息应答事件,表示发送消息成功后，调用这个方法
     */
    public void messageSent(IoSession session, Object message) throws Exception {
        logger.debug("报文下发完成！  ");
        // session.close(true);
    }


    public void inputClosed(IoSession session) throws Exception {
        RtuServer.getInstance().getSessionManager().removeSession(session);
        logger.debug("inputClosed 关闭会话" + session.getRemoteAddress());
    }
}
